import React, { useEffect } from 'react';
import { connect } from 'dva';
import { Table, Button, Tooltip } from 'antd';
import {
  InfoCircleOutlined,
  EditOutlined,
  DeleteOutlined,
  PlusCircleOutlined,
  DownloadOutlined,
} from '@ant-design/icons';
import moment from 'moment';
import './index.less';
import '../assets/incofont.css';
import { useState } from 'react';
import AddDataSource from './components/AddDataSource';
import FileUpload from './components/basic/FileUpload';
import { save } from '@/utils/blob2file';

function DataResource(props) {
  // 控制modal的显示
  const [addModalVisible, setAddModalVisible] = useState(false);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [infoVisible, setInfoVisible] = useState(false);
  const [data_source_data, set_data_source_data] = useState({});
  const [tableData, setTableData] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const token =
    'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIxIiwiZXhwIjoxNjQ3MTQ2MjIxLCJpYXQiOjE2NDQ3MjcwMjF9.OajOZaSMi674di_dx1u5r86AcliW0y7GMApMbWdP4W4';

  useEffect(() => {
    console.log('组件加载时，运行一次该函数');
    getAllDataSource();
  }, []);

  const {
    dataSource: {},
    dispatch,
  } = props;

  const getAllDataSource = () => {
    dispatch({
      type: 'dataSource/getAllDataSource',
    }).then(res => {
      if (res && Array.isArray(res)) {
        setTableData(res);
      }
    });
  };
  // getAllDataSource();
  const handleInfo = record => {
    // 从后端接口获取数据
    // console.log(record);
    dispatch({
      type: 'dataSource/getDataSourceInfo',
      payload: {
        id: record.id,
      },
    }).then(res => {
      console.log('DataSource', res);
      if (res) {
        set_data_source_data(res);
        setInfoVisible(true);
      }
    });
    const data_example = {
      id: '92fe5035-44b0-44f3-8346-f14cb3bbc0e6',
      name: 'localhost',
      note: 'localhost',
      url:
        'jdbc:mysql://localhost:3306/dbapi?useSSL=false&characterEncoding=UTF-8&serverTimezone=GMT%2B8',
      username: 'root',
      password: 'password',
      type: 'mysql',
      driver: 'com.mysql.cj.jdbc.Driver',
      tableSql: 'show tables',
      createTime: '2022-01-17 18:04:28',
      updateTime: '2022-01-17 18:04:28',
    };
  };

  const handleEdit = record => {
    // 从后端接口获取数据之后，呈现修改
    // console.log(record);
    dispatch({
      type: 'dataSource/getDataSourceInfo',
      payload: {
        id: record.id,
      },
    }).then(res => {
      if (res) {
        set_data_source_data(res);
        setEditModalVisible(true);
      }
    });
  };

  const handleDel = record => {
    // 根据record的id直接请求后端删除记录
    console.log(record);
    dispatch({
      type: 'dataSource/deleteDataSource',
      payload: {
        id: record.id,
      },
    }).then(res => {
      if (res) {
        getAllDataSource();
      }
    });
  };

  const columns = [
    {
      title: '数据源ID',
      dataIndex: 'id',
      key: 'id',
      // width: '200px',
    },
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      // width: '150px',
    },
    {
      title: '描述',
      dataIndex: 'note',
      key: 'note',
      // width: '200px',
    },
    {
      title: '修改时间',
      key: 'updateTime',
      dataIndex: 'updateTime',
      // width: '200px',
      render: text => moment(text).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '操作',
      key: 'operation',
      render: (text, record) => (
        <div>
          <Tooltip placement="top" title="详细信息">
            <InfoCircleOutlined
              className="oper-icon"
              style={{ color: '#23d346' }}
              onClick={() => handleInfo(record)}
            />
          </Tooltip>

          <Tooltip placement="top" title="编辑">
            <EditOutlined
              className="oper-icon"
              style={{ color: '#1890ff' }}
              onClick={() => handleEdit(record)}
            />
          </Tooltip>
          <Tooltip placement="top" title="删除">
            <DeleteOutlined
              className="oper-icon"
              style={{ color: 'red' }}
              onClick={() => handleDel(record)}
            />
          </Tooltip>
        </div>
      ),
    },
  ];

  /**
   * 改变ModalVisible的值
   */
  const handleAddDataSource = () => {
    setAddModalVisible(true);
  };

  const handleExport = () => {
    console.log('handleExport..');
    dispatch({
      type: 'dataSource/exportDataSource',
      payload: {
        ids: selectedRowKeys.join(','),
      },
    }).then(res => {
      //可在此处打印res,看看有哪些返回数据
      save(res, 'data_source.json');
    });
  };

  const onSelectChange = selectedRowKeys => {
    console.log('选择的行', selectedRowKeys);
    setSelectedRowKeys(selectedRowKeys);
    setHasSelected(selectedRowKeys.length > 0);
  };

  const rowSelection = {
    selectedRowKeys: selectedRowKeys,
    onChange: onSelectChange,
  };

  const [hasSelected, setHasSelected] = useState(false);

  return (
    <div className="data-resource">
      <h2 className="big-font">数据源板块</h2>

      <div style={{ marginBottom: '20px' }}>
        <Button className="btns" onClick={() => handleAddDataSource()}>
          <PlusCircleOutlined style={{ marginLeft: '-8px' }} />
          新增
        </Button>
        {/*<Button className="btns" onClick={() => handleExport()}>*/}
        {/*  <UploadOutlined style={{marginLeft: '-8px'}}/>*/}
        {/*  导出*/}
        {/*</Button>*/}
        <FileUpload
          // url={'http://127.0.0.1:8520/datasource/import'}
          url={'http://121.4.195.203/server/datasource/import'}
          token={token}
          getAllDataSource={getAllDataSource}
        />
      </div>
      <h3 className="big-font">数据源列表</h3>

      <div>
        <div style={{ marginBottom: 16 }}>
          <Button className="btns" type="primary" onClick={handleExport} disabled={!hasSelected}>
            <DownloadOutlined style={{ marginLeft: '-8px' }} />
            导出数据源
          </Button>
        </div>

        <Table
          rowKey={record => record.id}
          rowSelection={rowSelection}
          columns={columns}
          dataSource={tableData}
        />
      </div>
      {/* Modal弹框的显示 */}
      {addModalVisible && (
        <AddDataSource
          setAddModalVisible={setAddModalVisible}
          addModalVisible={addModalVisible}
          edit={false}
          readOnly={false}
          getAllDataSource={getAllDataSource}
        />
      )}
      {editModalVisible && (
        <AddDataSource
          addModalVisible={editModalVisible}
          setAddModalVisible={setEditModalVisible}
          data={data_source_data}
          edit={true}
          readOnly={false}
          getAllDataSource={getAllDataSource}
        />
      )}
      {infoVisible && (
        <AddDataSource
          addModalVisible={infoVisible}
          setAddModalVisible={setInfoVisible}
          data={data_source_data}
          edit={true}
          readOnly={true}
        />
      )}
    </div>
  );
}

export default connect(({ dataSource }) => ({ dataSource }))(DataResource);
